package bc.swim2.ejb.session;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import bc.swim2.ejb.entity.Friendship;
import bc.swim2.ejb.entity.RegisteredUser;

/**
 * Session Bean implementation class AbilityRequestManagerBean
 */
@Stateless
public class FriendshipManagerBean implements FriendshipManagerBeanRemote {

	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;

	public FriendshipManagerBean() {
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Friendship> getFriendshipList() {
		List<Friendship> friendships = null;

		try {
			Query q = em.createNamedQuery("Friendship.getFriendshipList");
			friendships = (List<Friendship>) q.getResultList();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return friendships;
	}

	@SuppressWarnings("unchecked")
	public List<RegisteredUser> getFriendshipRequestList(RegisteredUser ru) {
		List<Friendship> friendshipRequests = null;
		List<RegisteredUser> frUsers = new ArrayList<>();

		try {
			Query q = em
					.createNamedQuery("Friendship.getFriendshipRequestList");
			q.setParameter("userId", ru.getId());
			friendshipRequests = (List<Friendship>) q.getResultList();

			Iterator<Friendship> it = friendshipRequests.iterator();

			while (it.hasNext()) {
				Friendship f = (Friendship) (it.next());
				int uid = f.getSenderId();

				try {

					List<RegisteredUser> tempUsers = null;
					Query q2 = em
							.createNamedQuery("RegisteredUser.getRegisteredUserById");
					q2.setParameter("id", uid);
					tempUsers = (List<RegisteredUser>) q2.getResultList();
					RegisteredUser usr = tempUsers.get(0);

					frUsers.add(usr);

				} catch (Exception e) {
					System.out.println(e.getMessage());
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return frUsers;
	}

	@SuppressWarnings("unchecked")
	public List<RegisteredUser> getFriendList(RegisteredUser ru) {
		List<Friendship> friendships = null;
		List<RegisteredUser> friends = new ArrayList<>();

		try {
			Query q = em.createNamedQuery("Friendship.getFriendList");
			q.setParameter("userId", ru.getId());
			friendships = (List<Friendship>) q.getResultList();

			for (Friendship f : friendships) {
				int sid = f.getSenderId();
				int rid = f.getReceiverId();
				int usid = ru.getId();
				int uid = -1;

				if ((sid == usid) && (rid != usid)) {
					uid = rid;
				} else if ((sid != usid) && (rid == usid)) {
					uid = sid;
				}

				try {

					List<RegisteredUser> tempUsers = null;
					Query q2 = em
							.createNamedQuery("RegisteredUser.getRegisteredUserById");
					q2.setParameter("id", uid);
					tempUsers = (List<RegisteredUser>) q2.getResultList();
					RegisteredUser usr = tempUsers.get(0);

					friends.add(usr);

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return friends;
	}

	@Override
	public void sendFriendshipRequest(RegisteredUser sender,
			RegisteredUser receiver, boolean ind) {

		try {
			Friendship newFriendship = new Friendship(sender.getId(),
					receiver.getId(), false, ind);
			em.persist(newFriendship);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void approveFriendshipRequest(RegisteredUser sender,
			RegisteredUser receiver) {
		Friendship friendship = null;
		try {
			Query q = em
					.createNamedQuery("Friendship.getFriendshipFromSenderIdAndReceiverId");
			q.setParameter("senderId", sender.getId());
			q.setParameter("receiverId", receiver.getId());
			friendship = (Friendship) q.getSingleResult();
			friendship.setConfirmed(true);
			em.merge(friendship);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void declineFriendshipRequest(RegisteredUser sender,
			RegisteredUser receiver) {
		Friendship friendship;
		try {
			Query q = em
					.createNamedQuery("Friendship.getFriendshipFromSenderIdAndReceiverId");
			q.setParameter("senderId", sender.getId());
			q.setParameter("receiverId", receiver.getId());
			friendship = (Friendship) q.getSingleResult();
			if (!(friendship.getConfirmed())) {
				em.remove(friendship);
			} else
				System.out.println("Hai gia' risposto a questa amicizia");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean friendshipAlreadySent(RegisteredUser sender,
			RegisteredUser receiver) {
		List<Friendship> friendships = null;

		Query q = em
				.createNamedQuery("Friendship.getFriendshipFromSenderIdAndReceiverId");
		q.setParameter("senderId", sender.getId());
		q.setParameter("receiverId", receiver.getId());
		friendships = (List<Friendship>) q.getResultList();
		if (friendships.isEmpty()) {
			return false;
		} else {
			return true;
		}
	}

	public Friendship getFriendship(RegisteredUser sender,
			RegisteredUser receiver) {

		Friendship friendship = null;

		Query q = em
				.createNamedQuery("Friendship.getFriendshipFromSenderIdAndReceiverId");
		q.setParameter("senderId", sender.getId());
		q.setParameter("receiverId", receiver.getId());
		friendship = (Friendship) q.getResultList().get(0);
		return friendship;
	}

	@SuppressWarnings("unchecked")
	public String getFriendshipState(int userId1, int userId2) {
		String fs = null;
		List<Friendship> friendships = null;
		Friendship friendship;
		Query q = em.createNamedQuery("Friendship.getFriendshipState");
		q.setParameter("userId1", userId1);
		q.setParameter("userId2", userId2);
		friendships = (List<Friendship>) (q.getResultList());
		if (friendships.isEmpty()) {
			fs = "noRequest";
		} else {
			friendship = friendships.get(0);
			if (friendship.getConfirmed()) {
				fs = "accepted";
			} else {
				fs = "pending";
			}
		}
		return fs;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RegisteredUser> getFrndshpNotVisualized(RegisteredUser user) {
		List<Friendship> friendshipRequests = null;
		List<RegisteredUser> frUsers = new ArrayList<>();

		try {
			Query q = em
					.createNamedQuery("Friendship.getFriendshipsNotVisualized");
			q.setParameter("userId", user.getId());
			friendshipRequests = (List<Friendship>) q.getResultList();

			for (Friendship f : friendshipRequests) {
				int uid = f.getReceiverId();

				try {

					List<RegisteredUser> tempUsers = null;
					Query q2 = em
							.createNamedQuery("RegisteredUser.getRegisteredUserById");
					q2.setParameter("id", uid);
					tempUsers = (List<RegisteredUser>) q2.getResultList();
					RegisteredUser usr = tempUsers.get(0);

					frUsers.add(usr);

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return frUsers;
	}

	@Override
	public void setVisualizedTrue(int friendshipId) {
		try {

			Query q = em.createNamedQuery("Friendship.setVisualizedTrueById");
			q.setParameter("id", friendshipId);

			@SuppressWarnings("unused")
			int updated = q.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}